use std::fs::*;
use std::io::prelude::*;
use std::path::*;
use log::{log,Level};

use thiserror::Error;
#[derive(Error, Debug)]
pub enum AliceIoError {
    #[error("目标路径不存在！")]
    Miss(String),
    #[error("文件 `{0}` 写入错误")]
    WriteFailed(String),
    #[error("文件 `{0}` 读取错误")]
    ReadFailed(String),
    #[error("unknown error")]
    Unknown,
}
pub struct AliceUtils;



/// io operator
impl AliceUtils {
    pub fn write_text_file(dir_path: impl AsRef<Path>, file_name: &str, content: &str) -> Result<(),AliceIoError> {
        let path = dir_path.as_ref().join(file_name);
        match read_dir(dir_path) {
            Ok(..) => match File::create(path) {
                Ok(mut file) => {
                   match file.write(content.as_bytes()) {
                        Ok(..)=> Ok(()),
                        Err(e) => Err(AliceIoError::Miss(e.to_string()))
                   }
                }
                Err(err) => {
                    log!(target: "IO", Level::Error, "写入文件错误: {:?}",
                    err);
                    Err(AliceIoError::WriteFailed(err.to_string()))
                }
            },
            Err(err) => {
                log!(target: "IO", Level::Error, "目标路径不是文件夹: {:?}",
                err);
                Err(AliceIoError::Miss("目标路径不是文件夹".to_string()))
            }
        }
    }

    /// 读取文件 如果目录不存在报错
    pub fn read_text_file(dir_path: impl AsRef<Path>, file_name: &str) -> Result<String,AliceIoError> {
        let path = dir_path.as_ref().join(file_name);
        match read_dir(dir_path) {
            Ok(..) => match read_to_string(path) {
                Ok(file) => {
                    Ok(file)
                }
                Err(err) => {
                    log!(target: "IO", Level::Error, "读取文件错误: {:?}",
                    err);
                    Err(AliceIoError::ReadFailed(err.to_string()))
                }
            },
            Err(err) => {
                log!(target: "IO", Level::Error, "目标路径不是文件夹: {:?}",
                err);
                Err(AliceIoError::Miss("目标路径不是文件夹".to_string()))
            }
        }
  
    }

     /// 读取文件 如果目录不存在报错
     pub fn read_text_file_unwrap(path: impl AsRef<Path>) -> Result<String,AliceIoError> {

        if path.as_ref().exists() {
            match read_to_string(path) {
                Ok(file) => {
                    Ok(file)
                }
                Err(err) => {
                    log!(target: "IO", Level::Error, "读取文件错误: {:?}",
                    err);
                    Err(AliceIoError::ReadFailed(err.to_string()))
                }
            }
        }else{
            log!(target: "IO", Level::Error, "目标路径不存在");
            Err(AliceIoError::Miss("目标路径不存在".to_string()))
        }
      
  
    }

  
}
